from typing import List

import pymysql


def insert(table, data):
    # 这里你知道table和data，其中data是一个字典，写插入数据库的代码
    column = data[0]
    cols = ", ".join('`{}`'.format(k) for k in column.keys())
    print(cols)  # '`name`, `age`'

    val_cols = ', '.join('%({})s'.format(k) for k in column.keys())
    print(val_cols)  # '%(name)s, %(age)s'
    sql = "insert into " + table + "(%s) values(%s)"
    res_sql = sql % (cols, val_cols)
    print(res_sql)
    return res_sql


# 数据库配置
host = '10.240.53.162'
port = 3306
user = 'rdsroot'
password = 'Geely@db20211206'
db_name = 'test'
charset = 'utf8mb4'  # 字符集设置


def insert_user_data(insert_data_list: List[dict]):
    if len(insert_data_list) == 0:
        return
    res_sql = insert("yy_user_like", insert_data_list)
    try:
        # 使用with语句管理连接和游标
        with pymysql.connect(host=host, port=port, user=user, password=password,
                             db=db_name, charset=charset) as db:
            with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
                # 执行多条插入语句
                cursor.executemany(res_sql, insert_data_list)

                # 提交事务
                db.commit()

                # 可以在这里添加其他数据库操作...

    except pymysql.MySQLError as e:
        print("MySQL错误:", e)


def insert_user_training(table, insert_data_list: List[dict]):
    if len(insert_data_list) == 0:
        return
    res_sql = insert(table, insert_data_list)
    try:
        # 使用with语句管理连接和游标
        with pymysql.connect(host=host, port=port, user=user, password=password,
                             db=db_name, charset=charset) as db:
            with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
                # 执行多条插入语句
                cursor.executemany(res_sql, insert_data_list)

                # 提交事务
                db.commit()

                # 可以在这里添加其他数据库操作...

    except pymysql.MySQLError as e:
        print("MySQL错误:", e)
